package com.hl.servlet;

import com.alibaba.fastjson.JSON;
import com.hl.bean.PanghuShop;
import com.hl.dao.StoreDao2;
import com.hl.dao.impl.StoreDaoImpl2;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@WebServlet("/shop/querySearchShopList")
public class SelectAllStoreServlet extends HttpServlet {
    //表格数据源连接
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //1.获取前端传递的分页信息 page size
        String pageString = req.getParameter("pageNum");
        int page = pageString == null ? 1 :Integer.parseInt(pageString);
        String sizeString = req.getParameter("pageSize");
        int size = sizeString == null ? 10 : Integer.parseInt(sizeString);
        //2.创建Map对象 用来给前端返回信息
        HashMap<String,Object> map = new HashMap<>();
        //3.查询数据总条数---增删改来自Dao
        StoreDao2 storeDao2 = new StoreDaoImpl2();
        Long count = storeDao2.selectAllStoreCount();
        //将数量存储到map中
        map.put("total",count);
        //4.按照分页查询数据
        List<PanghuShop> shops = storeDao2.selectAllStoreWithPage(page,size);
        System.out.println(shops);
        //将数据以键值对 存储map中
        map.put("list",shops);
        //5.设置code状态码 200成功 300 失败 以及message信息
        if ( shops != null){
            map.put("code",200);
            map.put("message","请求成功");
        }else {
            map.put("code",300);
            map.put("message","获取数据失败");
        }
        //6.将数据源map 通过response返回给前端
//.json是文件存储数据的一种格式 参考.txt .word等,仅仅是一种文件格式 但是因为其内部遵循键值对{}和数组[]结果;所以我们在进行网络数据输出都会使用此格式的数据进行传递
        String jsonString = JSON.toJSONString(map);
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write(jsonString);

    }
}
